package cn.tedu._05article_test.base.exception;

import cn.tedu._05article_test.base.response.JsonResult;
import cn.tedu._05article_test.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

import javax.validation.ConstraintViolationException;
import java.net.BindException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){

//        List<String> errors = ex.getConstraintViolations().stream()
//                .map(violation -> violation.getMessage())
//                .collect(Collectors.toList());
//        String data = String.join(", ", errors);
//        log.error("doHandleConstraintViolationException: {}", data);
//        return new JsonResult(StatusCode.VALIDATION_ERROR, data);
        String data = ex.getMessage().split(":")[1].trim();
        System.out.println(data);
        log.error("doHandleConstraintViolationException"+data);

        return new JsonResult(StatusCode.VALIDATION_ERROR,data);
    }
//    @ExceptionHandler
//    public JsonResult doHandlerIllegalArgumentException(IllegalArgumentException ex){
//        String data = ex.getMessage();
//        log.error("doHandlerIllegalArgumentException"+data);
//        return new JsonResult(StatusCode.OPERATION_FAILED,data);
//    }
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
//        String data = ex.getMessage();
        String data = ex.getFieldError().getDefaultMessage();      //只有这样写才能获得message消息
        log.error("doHandle"+data);
        return new JsonResult(StatusCode.VALIDATION_ERROR,data);
    }
//    @ExceptionHandler
//    public JsonResult doHandleRuntimeException(RuntimeException er){
//        String data = er.getMessage();
//        log.error("doHandleRuntimeException"+data);
//        return new JsonResult(StatusCode.OPERATION_FAILED,data);
//    }
//    @ExceptionHandler(BindException.class)
//    public JsonResult doHandleBindException(BindException ex) {
//
//        String data = ex.getMessage();
//        log.error("BindException: {}", data);
//        return new JsonResult(StatusCode.VALIDATION_ERROR, data);
//    }
}
